System Design Interview Crash Course
Rate this course
Ask Author
Contribute
Back to course home

59% completed

Vote For New Content
Introduction
Course Overview
Who this Course Is for
How to Cover the Lessons
Day 1: Content Delivery & Media
Design YouTube
Design Netflix
Day 2: Key-Value & Caching Internals
Design a Distributed Cache (like Redis)
Design a Key-Value Store (like DynamoDB)
Day 3: Chat & Real-time Communication
Design WhatsApp
Design Discord
Day 4: Reliability & Observability
Design a Distributed Rate Limiter
Design a Metrics & Monitoring System (like Datadog/Prometheus)
Day 5: Storage & Retrieval (Blob & File)
Design Amazon S3
Design Google Ads
Day 6: E-Commerce & Transactions
Design Amazon Shopping Cart
Design Stripe Payment Gateway
Design Stock Exchange
Day 7: Social Graph & Networking
Design Facebook “People You May Know”
Design LinkedIn Connections
Design Twitter Timeline
Day 8: Collaboration Tools
Design a Collaborative Whiteboard (Miro)
Design Google Docs
Design an Ad Click Aggregator
Design a Live Comment Streaming Service (Twitch Chat)
Design a Code Deployment System
Design an API Gateway
Design Amazon Lambda
Design ChatGPT
Design Typeahead/Autocomplete
Design Google Search
Design AirBnB
Design Uber/Lyft
Design a Distributed Lock Manager (like Chubby)
Design a Distributed Job Scheduler (like Cron)
Final Words
Design Google Docs
Image

Here is a detailed system design for Google Docs.

1. Problem Definition and scope

We are designing a cloud-based, real-time collaborative document editor.

The core challenge is allowing multiple users to edit the same text file simultaneously, ensuring everyone sees the same content eventually without data loss or conflicts.

  • Main User Groups: Document creators, editors, and read-only viewers.

  • Main Actions: Creating documents, typing text (insert/delete), and viewing changes from others in real-time.

  • Scope:

    • In Scope: The real-time editing engine (concurrency control), document storage, history/versioning, and cursor presence.

    • Out of Scope: Google Drive folder management, complex rich text formatting (tables, pagination), offline conflict resolution, and commenting systems.

Image

2. Clarify functional requirements

Must Have

  • Real-time Editing: Multiple users can edit the document concurrently. Changes appear instantly.

  • Conflict Resolution: The system handles simultaneous edits (e.g., two users typing at index 0) so that all clients converge to the same state.

  • Presence: Users see the cursors and names of other active collaborators.

  • Auto-save: Changes are persisted automatically; no manual "Save" button.

  • History: Users can view and restore previous versions of the document.

Nice to Have

  • Read-only Mode: Public links for viewing only.

  • Typing Indicators: Showing "User A is typing..."

Image

3. Clarify non-functional requirements

  • Target Users: 10 million Daily Active Users (DAU).

  • Concurrency: High. Assume 10% concurrent usage at peak (1 million active users).

  • Latency:

    • Local: < 10ms (optimistic updates).
    • Remote: < 200ms (for collaborators to see changes).
  • Consistency: Strong consistency eventually. All users connected to a document must see the exact same characters in the same order.

  • Availability: High (99.9%).

  • Read vs Write: Extremely write-heavy during active sessions (every keystroke is a write). Read-heavy for loading documents.

Image

4. Back of the envelope estimates

  • Traffic Estimate:
    • 1M concurrent users at peak.
    • If active users type ~1 character/second, that is 1 Million Write Operations Per Second (QPS).
    • This requires a highly optimized WebSocket layer.
  • Storage Estimate:
    • Average document text: 20 KB.
    • Operation Logs: The history of changes is much larger than the text. Assume 100 KB of log data per active doc/day.
    • 10M DAU * 5% creating docs = 500k new docs/day.
    • 500k * 100 KB = 50 GB/day.
    • Per year: ~18 TB. This is very manageable.
  • Bandwidth:
    • Operations are tiny JSON packets (< 100 bytes).
    • 1M QPS * 100 bytes = 100 MB/s. Bandwidth is not the bottleneck; CPU (for conflict resolution) and Connection Management are.
Image

5. API design

We use REST for document management and WebSockets for the high-frequency editing session.

REST API (Management)

  • POST /api/v1/documents
    • Request: { "title": "My Doc", "owner_id": "u123" }
    • Response: { "doc_id": "d555", "created_at": "..." }
  • GET /api/v1/documents/{doc_id}
    • Response: { "doc_id": "d555", "snapshot": "Full text content...", "version": 105 }
    • Note: Used to load the document state before connecting to the socket.

WebSocket API (Real-time Session)

  • CONNECT /ws/documents/{doc_id}
    • Establishes a persistent bi-directional connection.
  • Client -> Server:
    • edit_op: { "rev": 105, "op": "insert", "pos": 10, "char": "a" }
    • cursor: { "pos": 11, "user": "Alice" }
  • Server -> Client:
    • remote_op: { "rev": 106, "op": "insert", "pos": 10, "char": "a", "user": "Bob" }
    • ack: { "rev": 106 } (Confirms the server processed the edit).

6. High level architecture

We need a stateful architecture for the editing engine because conflict resolution (Operational Transformation) relies on a strictly ordered sequence of operations.

Client -> Load Balancer -> Collaboration Server -> Queue -> Database

  1. Client: The browser running the editor. It applies local changes immediately ("Optimistic UI") and sends them to the server.
  2. Load Balancer: Routes traffic.
    • Crucial: Must support Sticky Sessions (based on doc_id) or use a routing layer. All users editing "Doc A" must be routed to the same server instance.
  3. Collaboration Service (The Engine): A cluster of stateful servers.
    • Holds the In-Memory State of active documents (text + recent history).
    • Performs Operational Transformation (OT) to resolve conflicts.
    • Broadcasts updates to all connected clients.
  4. Session Cache (Redis): Stores doc_id -> server_ip mapping so the Load Balancer knows where to route a user.
  5. Message Queue (Kafka): Buffers operations from the Collaboration Service to be persisted asynchronously. Decouples fast editing from slow DB writes.
  6. Database: Stores the permanent history (Operation Log) and document snapshots.
Image

7. Data model

We use a NoSQL Database (like DynamoDB or Cassandra) because it handles high write throughput for append-only logs and scales horizontally.

Table 1: Operations_Log

Stores every single edit ever made. This is the Source of Truth.

  • doc_id (Partition Key)
  • version (Sort Key) - e.g., 101, 102, 103...
  • op_data (JSON) - e.g., {"op": "ins", "pos": 5, "val": "h"}
  • user_id
  • timestamp

Table 2: Document_Snapshots

Stores the full text periodically (e.g., every 100 ops) to speed up loading.

  • doc_id (Partition Key)
  • version (Sort Key)
  • content (Blob/Text)

Why Snapshots?

When a user opens a doc with 50,000 edits, we load the latest snapshot (Rev 49,900) and replay only the last 100 ops, rather than replaying 50,000 ops from scratch.

8. Core flows end to end

In a standard web app, a "save" is a simple database update. In a real-time collaborative editor, the logic is far more complex because the "Source of Truth" moves from the database to the active server memory during the session.

We will visualize the system through four critical flows:

  1. Document Loading: How we efficiently reconstruct the document state.
  2. Real-time Editing: Handling the "Happy Path" (latency compensation).
  3. Conflict Resolution: The "Operational Transformation" logic when users type over each other.
  4. Asynchronous Persistence: Saving data without slowing down the user.

Flow 1: Document Loading ("Hydration")

When a user opens a document, they need the latest version immediately. However, a document might be composed of millions of past operations. Replaying the entire history from scratch is too slow. We use a Snapshot + Replay strategy.

  1. Routing (Session Check):
  • The Load Balancer checks a Session Cache (Redis) to see if doc_id is already active on a specific Collaboration Server.
  • If Active: The user is routed to that specific server to ensure all collaborators are on the same machine.
  • If Inactive: The Load Balancer assigns a new server to host this document.
  1. Snapshot Retrieval:
  • The server queries the Document_Snapshots table for the most recent full backup (e.g., Version 5,000).
  1. Log Replay:
  • The server queries the Operations_Log table for all operations that occurred after Version 5,000 (e.g., Ops 5,001 to 5,050).
  1. State Reconstruction:
  • The server loads the snapshot into RAM and applies the 50 recent operations. The document is now "Hydrated" at Version 5,050.
  1. Connection Upgrade:
  • The server sends the full text to the client. The client renders it and upgrades the connection to a WebSocket for real-time updates.
Image

Flow 2: Real-time Editing (The "Happy Path")

This scenario handles the standard typing experience where there is no conflict. We use Optimistic UI to ensure the editor feels responsive (0ms latency).

  1. User Action: User Alice types "A" at index 0.
  2. Optimistic Local Update:
  • Alice's browser applies the change immediately. The user sees "A" instantly.
  • Alice's Client sends the operation to the Server: { op: "insert", char: "A", pos: 0, v: 100 }.
  1. Server Validation:
  • The Server receives the operation. It verifies that the base version (v: 100) matches the server's current version.
  1. Broadcast:
  • The Server accepts the change, increments the version to 101, and broadcasts the message to all other connected clients (Bob, Charlie).
  1. Sync:
  • Bob's client receives the message, inserts "A" at index 0, and updates its version to 101. Everyone is now in sync.
Image

Flow 3: Conflict Resolution (Operational Transformation)

This is the core complexity of the system. It handles the race condition where two users edit the same spot at the exact same time.

The Scenario: The document text is "CAT" (Version 100).

  • User A types "S" at the end to make "CATS" (Insert "S" at index 3).
  • User B types "A" at the start to make "ACAT" (Insert "A" at index 0).
  • Both users type simultaneously.

Step-by-Step Resolution:

  1. The Winner (User B): The Server receives User B's operation first.
  • Server checks version: 100 matches 100.
  • Server applies "Insert A at 0". Text becomes "ACAT".
  • Server Version increments to 101.
  • Server broadcasts User B's op to User A.
  1. The Conflict (User A): The Server receives User A's operation next.
  • Mismatch: User A sent an operation based on Version 100, but the Server is now at Version 101.
  • The Problem: User A wanted to insert "S" at index 3. However, because User B inserted a character at the start, the index 3 in the old document corresponds to index 4 in the new document.
  • If we blindly inserted at 3 now, we would get "ACAST" (Incorrect). We want "ACATS".
  1. Transformation (OT):
  • The Server runs the Transform Function: Transform(New_Op, Previous_Op).
  • Logic: "Since the previous operation inserted 1 character before Alice's target position, Alice's target position must be shifted by +1."
  • Result: User A's operation is transformed from pos: 3 to pos: 4.
  1. Convergence:
  • Server applies the transformed op. Text becomes "ACATS".
  • Server sends the transformed op back to User A (acknowledging their edit) and broadcasts it to User B.
  • Result: Both users see "ACATS".
Image

Flow 4: Asynchronous Persistence (Write-Behind)

Writing to a database is slow (milliseconds), while typing is fast (microseconds). To prevent the editor from lagging, we decouple "Editing" from "Saving."

  1. In-Memory Update: The Collaboration Server applies the operation to the document state in RAM. This is the "Source of Truth" for active sessions.

  2. Queue Push: The server pushes the operation JSON into a message queue (e.g., Kafka). This is extremely fast (< 5ms).

  3. Client Ack: The server sends an acknowledgment to the client immediately after the queue push. We do not wait for the database write.

  4. Save Worker: A separate background worker reads a batch of operations from Kafka (e.g., 50 ops) and appends them to the Operations_Log table in the database (DynamoDB).

  5. Snapshot Update: Every N operations (e.g., 500), the worker triggers a job to save the full text to the Snapshots table. This ensures Flow 1 (Loading) remains fast as the document ages.

Image

9. Caching and read performance

  • In-Memory "Cache": The Collaboration Server is the cache for active documents. It holds the latest state in RAM to process ops in nanoseconds.

  • Redis (Routing): Used by the Load Balancer to find which server hosts doc_id.

  • Client-Side Cache: The browser buffers unacknowledged ops. If the internet drops, the client keeps the ops and re-sends them in a batch upon reconnection.

10. Storage, indexing and media

  • Indexing: The Operations_Log is indexed by doc_id and version. This allows efficient queries like "Get all ops for Doc A from version 500 to 600".

  • Media (Images):

    • We do not store binary data in the operation log.
    • Client uploads image to Object Storage (S3/GCS) directly via a presigned URL.
    • S3 returns a URL (e.g., https://s3.../image.jpg).
    • Client sends a text operation: insert_element({ type: "image", src: "https://s3..." }) at position X.
    • The document just stores the reference URL.

11. Scaling strategies

  • Sharding by Document ID:
    • The unit of scale is the Document, not the User.
    • We use Consistent Hashing to distribute documents evenly across the Collaboration Servers.
  • Handling "Hot" Documents (The "10k Viewers" Problem):
    • If 10,000 users open one doc (e.g., a public release note), a single server cannot handle 10k WebSocket connections.
    • Strategy: Split Editors vs Viewers.
      • Editors (Active): Connect to the "Master" node (limited to ~100 users).
      • Viewers (Read-only): Connect to "Relay" nodes. The Master node pushes updates to Relays, which fan out to thousands of viewers.

12. Reliability, failure handling and backpressure

  • Server Crash:
    • If Server_A (hosting doc_1) crashes, the in-memory state is lost.
    • Recovery:
      1. Clients disconnect and reconnect.
      2. Load Balancer assigns doc_1 to Server_B.
      3. Server_B reads the latest Snapshot + Ops Log from the Database to reconstruct the state.
      4. Clients re-sync.
  • Data Safety:
    • We use a Write-Ahead Log or push to Kafka before sending the ack to the client. This ensures that even if the app server crashes, the data is safe in the queue.
  • Rate Limiting:
    • Limit incoming operations to ~20-30 ops/sec per user to prevent scripts from flooding the OT engine.

13. Security, privacy and abuse

  • Authentication: OAuth 2.0 / JWT. The token is sent during the WebSocket handshake.

  • Authorization: The server checks an Access Control List (ACL) in the database (permissions table) before upgrading the connection to a WebSocket.

  • Encryption: TLS (WSS) for all data in transit. AES-256 for data at rest in the DB.

  • Abuse: Limit maximum document size (e.g., 2 million characters) to prevent storage exhaustion attacks.

14. Bottlenecks and next steps

  • Bottleneck: OT Complexity. The OT algorithm requires a single central coordinator per document. This limits the max active writers per doc.

    • Next Step: Investigate CRDTs (Conflict-free Replicated Data Types). CRDTs allow decentralized peer-to-peer merging, removing the single-server bottleneck, though they are more complex and memory-intensive.
  • Bottleneck: Global Latency. Users in Asia editing a document hosted in the US will experience lag.

    • Next Step: Dynamically migrate the active document session to a data center closest to the majority of current active editors.

Summary

  1. Concurrency: Solved using Operational Transformation (OT) on a stateful server per document.

  2. Storage: NoSQL for append-only operation logs, enabling reliable history.

  3. Scale: Sharding by Document ID allows horizontal scaling to millions of documents.

  4. Performance: WebSockets and in-memory state ensure low latency (<200ms) for real-time collaboration.

Design a Collaborative Whiteboard (Miro)
Design an Ad Click Aggregator
Mark as Completed

On this page

1. Problem Definition and scope

2. Clarify functional requirements

3. Clarify non-functional requirements

4. Back of the envelope estimates

5. API design

6. High level architecture

7. Data model

8. Core flows end to end

Flow 1: Document Loading ("Hydration")

Flow 2: Real-time Editing (The "Happy Path")

Flow 3: Conflict Resolution (Operational Transformation)

Flow 4: Asynchronous Persistence (Write-Behind)

9. Caching and read performance

10. Storage, indexing and media

11. Scaling strategies

12. Reliability, failure handling and backpressure

13. Security, privacy and abuse

14. Bottlenecks and next steps

Summary